package com.example.demo.yuy.demo.controller;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.LRUCache;
import cn.hutool.core.io.FileUtil;
import com.example.demo.pdf.PDFUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 描述
 *
 * @author: yuy
 */
@RestController
@Slf4j
public class PdfController {

    private static String UPLOAD_PATH = "/Users/deck/Desktop/files/Git.pdf";

    private static LRUCache<String, byte[]> cache = CacheUtil.newLRUCache(8);


    @GetMapping("pdf")
//    @WebLog
    public void pdfView(HttpServletResponse response) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String markName = "黄俊亮-" + format.format(new Date()) + "-11056006";
        PDFUtils.markPdf(response, UPLOAD_PATH, markName);
    }




    @GetMapping("pdfCache")
//    @WebLog   // 入参转json报错
    public void pdfCache(HttpServletResponse response) throws IOException {
        File file = new File(UPLOAD_PATH);
        if (null == cache.get("pdfCache")) {
            cache.put("pdfCache", FileUtil.readBytes(file));
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "pdfTest" + "\"");
        OutputStream outputStream = response.getOutputStream();
        outputStream.write(cache.get("pdfCache1"));
        outputStream.flush();
        outputStream.close();
    }

}
